package com.topisv.tms.utils;

import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;

import com.topisv.tms.entity.User;

/**
 * 密码操作类
 * @author Administrator
 *
 */
public class DigestsUtils {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	public static final int SALT_SIZE = 8;
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	public static void entryptPassword(User user) {
		byte[] salt = getSalt();
		user.setSalt(Encodes.encodeHex(salt));
		byte[] hashPassword = getHashPassword(user.getPlainPassword(), salt);
		user.setPassword(getPassword(hashPassword));
	}
	
	/**
	 * 根据字符串生成相应的加密密码
	 * @param password
	 * @param salt
	 * @return
	 */
	public static String getPassWord(String password,String salt){
		byte[] saltBytes = Encodes.decodeHex(salt);
		byte[] hashPassword = getHashPassword(password, saltBytes);
		return getPassword(hashPassword);
		
	}
	
	private static String getPassword(byte[] hashPassword ){
		return Encodes.encodeHex(hashPassword);
	}
	
	private static byte[] getHashPassword(String password,byte[] salt){
		return Digests.sha1(password.getBytes(), salt, HASH_INTERATIONS);
	}
	
	private static byte[] getSalt(){
		return Digests.generateSalt(SALT_SIZE);
	}

}
